package com.smartrobot.smartrobot.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.smartrobot.smartrobot.R;

/**
 * 下拉显示更新 ， 到底部显示加载 listview
 * @author Administrator
 *
 */
public class ExTopListView extends ListView implements OnScrollListener{

    final int PULL_TO_REASHING = 0;
    final int RELASE_TO_REFASHING = 1;
    final int REFASHING = 2;
    final int DONE = 3;

    private Context context;
    private RelativeLayout headTitle;

    private ImageView headPic;
    private TextView headTxt;
    private ProgressBar headBar;
    private int startY=0,endY=0;
    //设置动画
    private RotateAnimation animation,relaseAnimation;
    private int state = 0;
    private int turnFlag = 0;
    private int firstItemIndex;
    private boolean isEnd = false;

    private int scrollHeight;
    private boolean isRecord = false;

    private Handler handler;


    private boolean upToDown = false;
    private boolean downToUp = false;
    private boolean isHasHead = false;


    private UdateNewListener newListener = null;
    private UdateOldListener oldListener = null;


    public ExTopListView(Context _context, AttributeSet attrs, int defStyle) {
        super(_context, attrs, defStyle);
        context = _context;
        init();
    }

    public ExTopListView(Context _context, AttributeSet attrs) {
        super(_context, attrs);
        context = _context;
        init();
    }

    public ExTopListView(Context _context) {
        super(_context);
        context = _context;
        init();
    }

    //判断是否到达底部
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        firstItemIndex = firstVisibleItem;

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {



    }

    public void init()
    {

        //添加一个头部的通知框
        headTitle = (RelativeLayout)LayoutInflater.from(context).inflate(R.layout.pull_refash_view ,null);
        headTitle.setPadding(headTitle.getPaddingLeft(), -999,
                headTitle.getPaddingRight(), headTitle.getPaddingBottom());
        headTitle.invalidate();
        this.addHeaderView(headTitle);


        headPic = (ImageView)headTitle.findViewById(R.id.pullrefash_pic);
        headPic.setVisibility(VISIBLE);
        headTxt = (TextView)headTitle.findViewById(R.id.pullrefash_text);
        headBar = (ProgressBar)headTitle.findViewById(R.id.head_refashing_bar);

        //将获取得焦点时设置透明，取出显示蓝色现象
        this.setSelector(new ColorDrawable(Color.TRANSPARENT));

        //旋转180动画
        animation = new RotateAnimation(0, -180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(100);
        animation.setFillAfter(true);
        //恢复原画
        relaseAnimation = new RotateAnimation(-180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        relaseAnimation.setInterpolator(new LinearInterpolator());
        relaseAnimation.setDuration(100);
        relaseAnimation.setFillAfter(true);

        scrollHeight = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight()/4;

        isEnd = false;
        this.setOnScrollListener(this);

    }

    public void changeState()
    {

        switch(state)
        {
            case PULL_TO_REASHING:break;
            case RELASE_TO_REFASHING:break;
            case REFASHING:
            {


                //對head進行操作 正在更新不要改变
                if(firstItemIndex == 0){
                    state = DONE;
                    headTxt.setText(R.string.head_refashing);
                    headPic.setVisibility(GONE);
                    headPic.clearAnimation();
                    headBar.setVisibility(VISIBLE);
                    headTitle.setPadding(headTitle.getPaddingLeft(), 1,
                            headTitle.getPaddingRight(), headTitle.getPaddingBottom());
                    headTitle.invalidate();

                    if(newListener != null){
                        newListener.updateNew();
                    }



                }

            }break;

            case DONE:{

                if(isHasHead) {
                    this.removeHeaderView(headTitle);
                    isHasHead = false;
                }

                //對頭部和尾部進行分開操作
                if(firstItemIndex == 0){
                    headPic.clearAnimation();
                    headPic.startAnimation(relaseAnimation);
                    headPic.setVisibility(VISIBLE);
                    headBar.setVisibility(GONE); //隐藏加载 显示向下拉图片
                    headTxt.setText(R.string.head_pull_refash);
                    headTitle.setPadding(headTitle.getPaddingLeft(), -999,
                            headTitle.getPaddingRight(), headTitle.getPaddingBottom());
                    headTitle.invalidate();
                }

            }
            break;
        }

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch(event.getAction())
        {

            case MotionEvent.ACTION_DOWN:
                if(!isRecord){//如果没有记录是记录一次
                    startY = (int)event.getY();
                    isRecord = true;
                }

                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                isRecord = false;
                changeState();

                break;
            case MotionEvent.ACTION_MOVE:{

                endY = (int)event.getY();//解决嵌套布局夺取点击事件
                if(!isRecord){//如果没有记录是记录一次
                    startY = (int)event.getY();
                    isRecord = true;
                }
                //判断滑动
                if(startY - endY  > 10 ) downToUp = true;
                else downToUp = false;



                headTitle.setPadding(headTitle.getPaddingLeft(), -999,
                        headTitle.getPaddingRight(), headTitle.getPaddingBottom());
                headTitle.invalidate();

                //在listview最上面才执行headTitle
                if(firstItemIndex == 0){

                    Log.e("=============startY==================>"," "+ startY);
                    Log.e("===============endY================>"," "+ endY);
                    Log.e("===============================>"," "+ (endY - startY));

                    if(endY - startY >10) {

//                    if(startY == 0) startY = endY;
                        headBar.setVisibility(View.GONE);
                        headPic.setVisibility(VISIBLE);
                        headTitle.setPadding(headTitle.getPaddingLeft(), (endY - startY) / 4,//减小拉伸距离，减小刷新界面
                                headTitle.getPaddingRight(), headTitle.getPaddingBottom());
                        headTitle.invalidate();


                        if (endY - startY >= scrollHeight) {
                            state = REFASHING;
                            if (!headTxt.getText().equals(
                                    getResources().getString(R.string.head_realse_refash)))
                                turnFlag = 1;
                            headTxt.setText(R.string.head_realse_refash);
                        } else {
                            state = DONE;
                            if (!headTxt.getText().equals(
                                    getResources().getString(R.string.head_pull_refash)))
                                turnFlag = 2;
                            headTxt.setText(R.string.head_pull_refash);
                        }

                        switch (turnFlag) {
                            case 0:
                                break;
                            case 1: {
                                turnFlag = 0;
                                headPic.clearAnimation();
                                headPic.startAnimation(animation);

                            }
                            break;
                            case 2: {
                                turnFlag = 0;
                                headPic.clearAnimation();
                                headPic.startAnimation(relaseAnimation);


                            }
                            break;

                        }

                    }

                }
            }
            break;

        }
        return super.onTouchEvent(event);
    }


    // 计算headView的width及height值
    private void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
                    MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    public void setHandler(Handler handler){

        this.handler = handler;

    }




    //设置接口用作处理 加载最新和看历史
    public interface UdateNewListener{
        void updateNew();
    }

    public interface UdateOldListener{
        void updateOld();
    }

    public void setOnUdateNewListender(UdateNewListener listener){

        this.newListener = listener;
    }

    public void setOnUdateOldListener(UdateOldListener listener){

        this.oldListener = listener;
    }

    public void removeHead(){

        this.removeHeaderView(headTitle);

    }






}
